﻿using System;
using System.Collections.Generic;
using Gumini.JulaDB.Enums;
using Gumini.JulaDB.Provider;

namespace Gumini.JulaDB.Data
{
    [Serializable]
    public class Database
    {
        /// <summary>
        /// A dictionary mapping from table name to table data and definition.
        /// All names are normalized to lowercase.
        /// </summary>
        private readonly Dictionary<string, Table> _tables = new Dictionary<string, Table>();
        
        public void CreateTable(TableDefinition definition)
        {
            var lowercaseName = definition.Name.ToLowerInvariant();
            if (_tables.ContainsKey(lowercaseName))
                throw new JulaDbException(ErrorCode.DuplicateTableName, "Table '{0}' already exists.", definition.Name);
            
            var table = new Table(definition);
            _tables.Add(lowercaseName, table);
        }

        public void DropTable(string tableName)
        {
            var lowercaseName = tableName.ToLowerInvariant();
            if (!_tables.ContainsKey(lowercaseName))
                throw new JulaDbException(ErrorCode.UnknownTable, "Table '{0}' does not exist.", tableName);

            _tables.Remove(lowercaseName);
        }

        public Table GetTable(string tableName)
        {
            var lowercaseName = tableName.ToLowerInvariant();
            if (!_tables.ContainsKey(lowercaseName))
                throw new JulaDbException(ErrorCode.UnknownTable, "Table '{0}' does not exist.", tableName);

            return _tables[lowercaseName];
        }
    }
}
